<template>
  <el-table :data="arr">
    <el-table-column type="index" label="编号" width="60px"></el-table-column>
    <el-table-column prop="username" label="用户名"></el-table-column>
    <el-table-column prop="nickname" label="昵称"></el-table-column>
    <el-table-column label="头像">
<!--   scope.row得到当前行对应的数组里面的对象   -->
      <template #default="scope">
        <el-avatar :src="BASE_URL+scope.row.imgUrl"></el-avatar>
      </template>
    </el-table-column>
    <el-table-column label="管理员">
      <template #default="scope">
        <el-switch @change="adminChange(scope.row)" v-model="scope.row.isAdmin"></el-switch>
      </template>
    </el-table-column>
    <el-table-column prop="createTime" label="创建时间"></el-table-column>
    <el-table-column label="操作">
      <template #default="scope">
        <el-button type="danger" @click="del(scope.$index,scope.row)">删除</el-button>
      </template>
    </el-table-column>
  </el-table>
</template>

<script setup>
import {onMounted, ref} from "vue";
import axios from "axios";
import qs from "qs";
import {ElMessage} from "element-plus";

const del = (i,user)=>{
  let currentUser = getUser();
  if (user.id==currentUser.id){
    ElMessage.error("不能删除当前用户!");
    return;
  }
  if (confirm("您确认删除此用户吗?")){
    axios.post(BASE_URL+'/v1/users/'+user.id+"/delete").then((response)=>{
      if (response.data.code==2001){
        ElMessage.success("删除完成!");
        arr.value.splice(i,1);//删除数组中的内容
      }
    })
  }
}

  const adminChange=(user)=>{
    let u = {id:user.id,isAdmin:user.isAdmin?1:0};
    let data = qs.stringify(u);
    axios.post(BASE_URL+'/v1/users/change',data).then((response)=>{
      if (response.data.code==2001){
        ElMessage.success("修改完成!");
      }
    })
  }

  const arr = ref([]);

  onMounted(()=>{
    //发请求获取用户列表
    axios.get(BASE_URL+'/v1/users').then((response)=>{
      if (response.data.code==2001){
        arr.value = response.data.data;
      }
    })
  })
</script>

<style scoped>

</style>